package com.aplikata.evok.ui;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.hibernate.criterion.Order;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.TreeNode;

import com.aplikata.bo.Role;
import com.aplikata.constants.Constants;
import com.aplikata.constants.ConstantsMsg;
import com.aplikata.dataModel.RoleDataModel;
import com.aplikata.evok.service.EvokTherapyService;
import com.aplikata.ui.UIBean;
import com.aplikata.util.FacesUtil;

@ManagedBean(name = "therapyRoleBean")
@ViewScoped
public class EvokTherapyRoleBean extends UIBean {

	private static final long serialVersionUID = 1L;

	@ManagedProperty(value = "#{evokTherapyService}")
	private EvokTherapyService therapyService;

	private RoleDataModel roleModel;
	private List<Role> roleList;

	private Role role;
	private TreeNode rootNode;
	private TreeNode[] selectedNodes;
	
	@PostConstruct
	public void init() {
		role = new Role();
	}
	
	public void selectRole(SelectEvent event) {
		role = (Role) event.getObject();
		rootNode = null;
		rootNode = this.getRootNode();
	}
	
	public void submit() {
		try {
			therapyService.updateRoleTherapy(role, selectedNodes);
			FacesUtil.addInfoMessage(ConstantsMsg.INFO_SUCCESS, new Object[] { role.getName() });
		} catch (Exception e) {
			FacesUtil.addActionException(e, log);
		}
	}

	public EvokTherapyService getTherapyService() { 
		return therapyService;
	}

	public void setTherapyService(EvokTherapyService therapyService) {
		this.therapyService = therapyService;
	}

	public RoleDataModel getRoleModel() {
		if (roleModel == null) {
			roleModel = new RoleDataModel(therapyService, getRoleList());
		}
		return roleModel;
	}

	public void setRoleModel(RoleDataModel roleModel) {
		this.roleModel = roleModel;
	}

	@SuppressWarnings("unchecked")
	public List<Role> getRoleList() {
		if (roleList == null) {
			roleList = (List<Role>) therapyService.findAll(Role.class, new Order[] { Order.asc(Role.NAME) });
		}
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public TreeNode getRootNode() {
		if(rootNode == null){
			rootNode = therapyService.getTherapyNodeTree(Constants.COMMON_STATUS_NORMAL, role.getId());
		}
		return rootNode;
	}

	public void setRootNode(TreeNode rootNode) {
		this.rootNode = rootNode;
	}

	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}

	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

}
